import React, {Component} from 'react';
import {
    FlatList,
    ActivityIndicator,
    Platform,
    StyleSheet,
    Text,
    View,
    RefreshControl,
    DeviceInfo,
    TouchableOpacity,
    DeviceEventEmitter,
} from 'react-native';
import { connect } from 'react-redux';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import actions from '../action/index';
import {
    createMaterialTopTabNavigator,
} from "react-navigation";
import TrendingDialog, {TimeSpans} from '../common/TrendingDialog';
import NavigationUtil from '../navigator/NavigationUtil';
import TrendingItem from '../common/TrendingItem';
import NavigationBar from '../common/NavigationBar';
import Toast from 'react-native-easy-toast';

const EVENT_TYPE_TIME_SPAN_CHANGE = 'EVENT_TYPE_TIME_SPAN_CHANGE';
const URL = 'https://github.com/trending/';
const THEME_COLOR = '#667788';

type Props = {};
export default class TrendingPage extends Component<Props> {
    constructor(props) {
        super(props);
        console.log(NavigationUtil.navigation);
        this.tabNames = ['All', 'C', 'C#', 'PHP', 'JavaScript'];
        this.state = {
            timeSpan: TimeSpans[0],
        }
    }

    _genTabs() {
        const tabs = {};
        this.tabNames.forEach((item, index) => {
            tabs[`tab${index}`] = {
                screen: props => <TrendingTabPage {...props} timeSpan={this.state.timeSpan} tabLabel={item}/>,
                navigationOptions: {
                    title: item
                }
            }
        });
        return tabs;
    }
    renderTitleView() {
        return <View>
            <TouchableOpacity
                underlayColor='transparent'
                onPress={() => this.dialog.show()}
            >
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <Text style={{fontSize: 18, color: '#FFFFFF', fontWeight: '400'}}>
                        趋势 {this.state.timeSpan.showText}
                    </Text>
                    <MaterialIcons
                        name={'arrow-drop-down'}
                        size={22}
                        style={{color: 'white'}}
                    />
                </View>
            </TouchableOpacity>
        </View>
    }

    onSelectTimeSpan(tab) {
        this.dialog.dismiss();
        this.setState({
            timeSpan: tab
        });
        // ** 2 **发送事件
        DeviceEventEmitter.emit(EVENT_TYPE_TIME_SPAN_CHANGE, tab);
    }

    renderTrendingDialog() {
        return <TrendingDialog
            ref={dialog => this.dialog=dialog}
            onSelect={tab => this.onSelectTimeSpan(tab)}
        />
    }

    _tabNav() {
        if (!this.tabNav) { // 没有时才创建，避免重复创建
            this.tabNav = createMaterialTopTabNavigator(
                this._genTabs(), {
                    tabBarOptions: {
                        tabStyle: styles.tabStyle,
                        upperCaseLabel: false,//是否使标签大写，默认为true
                        scrollEnabled: true,//是否支持 选项卡滚动，默认false
                        style: {
                            backgroundColor: '#678',//TabBar 的背景颜色
                            height: 30, // fix 开启 scrollEnabled 后 在安卓初次加载闪烁的问题
                        },
                        indicatorStyle: styles.indicatorStyle,//标签指示器的样式
                        labelStyle: styles.labelStyle,//文字的样式
                    }
                }
            );
        }
        return this.tabNav;
    }

    render() {
        let statusBar = {
            backgroundColor: THEME_COLOR,
            barStyle: 'light-content',
        };
        let navigationBar = <NavigationBar
            titleView={this.renderTitleView()}
            statusBar={statusBar}
            style={{backgroundColor: THEME_COLOR}}
        />;
        const TabNavigator = this._tabNav();
        return <View style={{flex: 1, marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0}}>
            {navigationBar}
            <TabNavigator/>
            {this.renderTrendingDialog()}
        </View>
    }
}

const pageSize = 10; // 设为常量，防止修改
class TrendingTab extends Component<Props> {

    constructor(props) {
        super(props);
        const { tabLabel, timeSpan } = this.props;
        this.storeName = tabLabel;
        this.timeSpan = timeSpan;
    }

    componentDidMount() {
        this.loadData();
        // ** 1 ** 监听事件
        this.timeSpanChangeListener = DeviceEventEmitter.addListener(EVENT_TYPE_TIME_SPAN_CHANGE, (timeSpan) => {
            this.timeSpan = timeSpan;
            this.loadData();
        })
    }

    componentWillUnmount(): void {
        // ** 3 ** 删除监听
        if (this.timeSpanChangeListener) {
            this.timeSpanChangeListener.remove();
        }
    }

    loadData(loadMore) {
        const { onRefreshTrending, onLoadMoreTrending } = this.props;
        const store = this._store();
        const url = this.genFetchUrl(this.storeName);
        if (loadMore) {
            onLoadMoreTrending(this.storeName, ++store.pageIndex, pageSize, store.items, () => {
                this.refs.toast.show('没有更多了');
            })
        } else {
            onRefreshTrending(this.storeName, url, pageSize);
        }
    }

    _store() {
        const {trending} = this.props;
        let store = trending[this.storeName];
        if (!store) {
            store = {
                items: [],
                isLoading: false,
                projectModes: [], // 要显示的数据
                hideLoadingMore: true, // 默认隐藏加载更多
            }
        }
        return store;
    }

    genFetchUrl(key) {
        return URL + key + '?' + this.timeSpan.searchText;
    }

    renderItem(data) {
        const item = data.item;
        return <TrendingItem
            item = {item}
            onSelect = {() => {
                NavigationUtil.goPage({
                    projectModel: item
                }, 'DetailPage')
            }}
        />
    }

    genIndicator() {
        return this._store().hideLoadingMore ? null :
            <View style={styles.indicatorContainer}>
                <ActivityIndicator
                    style = {styles.indicator}
                />
                <Text>正在加载更多..</Text>
            </View>
    }

    render() {
        const { trending } = this.props;
        let store = this._store(); // 动态获取state

        if (!store) {
            store = {
                items: [],
                isLoading: false,
            }
        }
        return (
            <View style={styles.container}>
                <FlatList
                    data={store.projectModes}
                    renderItem = {data => this.renderItem(data)}
                    keyExtractor = {item => "" + (item.id || item.fullName)}
                    refreshControl = {
                        <RefreshControl
                            title = {'Loading'}
                            titleColor = {THEME_COLOR}
                            colors = {[THEME_COLOR]}
                            refreshing = {store.isLoading}
                            onRefresh = {() => this.loadData()}
                            tintColor = {THEME_COLOR}
                        />
                    }
                    ListFooterComponent = { () => this.genIndicator()}
                    onEndReached = {() => {
                        console.log('---onEndReached----');
                        setTimeout(() => {
                            if (this.canLoadMore) {
                                this.canLoadMore = false;   // 不允许加载更多
                                this.loadData(true);
                            }
                        }, 100); // 防止意外 确保刷新在 滚动之后触发
                    }}
                    onEndReachedThreshold = {0.5}
                    onMomentumScrollBegin = {() => {   // 开始滚动，
                        this.canLoadMore = true;  // 只有滚动时，才打开加载更多开关, 避免 FlatList 首次加载就触发  '---onEndReached----'
                        console.log('---onMomentumScrollBegin----');
                    }}
                />
                <Toast ref = {'toast'}
                       position = {'center'}
                />
            </View>
        );
    }
}

const mapStateToProps = state => ({
    trending: state.trending
});

const mapDispatchToProps = dispatch => ({
    onRefreshTrending: (storeName, url, pageSize) => dispatch(actions.onRefreshTrending(storeName, url, pageSize)),
    onLoadMoreTrending: (storeName, pageIndex, pageSize, items, callBack) => dispatch(actions.onLoadMoreTrending(storeName, pageIndex, pageSize, items, callBack)),
});

const TrendingTabPage = connect(mapStateToProps, mapDispatchToProps)(TrendingTab);

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    tabStyle: {
        // minWidth: 50   // fix  minWidth 会导致 tabStyle 初次加载时闪烁
        padding: 0,
    },
    indicatorStyle: {
        height: 2,
        backgroundColor: 'white'
    },
    labelStyle: {
        fontSize: 13,
        margin: 0,
    },
    indicatorContainer: {
        alignContent: 'center',
    },
    indicator: {
        color: 'red',
        margin: 10
    },
});
